package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import model.Message;

class MessageReceiverThread extends Thread
{
	private static final String SOCKET_CLOSED = "socket closed";

	private static final String CONNECTION_RESET = "Connection reset";
	
	private ObjectInputStream objectInputStream;
	
	public MessageReceiverThread(final Socket socket) throws IOException
	{
		this.objectInputStream = new ObjectInputStream(socket.getInputStream());
	}
	
	public void close()
	{
		try
		{
			this.objectInputStream.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void run()
	{
		while (true) {
			try
			{
				Message message = (Message) objectInputStream.readObject();
				ClientMain.addMessage(message);
			}
			catch (IOException e)
			{
				if (e.getMessage() != null && e.getMessage().equals(CONNECTION_RESET))
				{
					ClientMain.clientViewController.printLog("Server suddenly closed.");
				}
				else if (e.getMessage() != null && e.getMessage().equals(SOCKET_CLOSED))
				{
					// socket was closed
				}
				else
				{
					ClientMain.clientViewController.printLog(e);
				}
				
				return;
			}
			catch (ClassNotFoundException e)
			{
				ClientMain.clientViewController.printLog(e);
				return;
			}
		}
	}
	
}
